//
//  OnlinePeopleView.m
//  tcpoctest
//
//  Created by gump on 5/15/13.
//  Copyright (c) 2013 gump. All rights reserved.
//

#import "OnlinePeopleView.h"
#import "SimpleSwitch.h"
#import "PersonCell.h"

#import "OnlinePeopleDataSource.h"

#import "sendOnlineP.h"
#import "taskDataSource.h"

enum OnLineGameState
{
    OLGS_START,
    OLGS_NULL,
};

@implementation OnlinePeopleView

- (id)init
{
    self = [super init];
    if (self) {
        iTimeCount = 0;
        iGameState = OLGS_NULL;
    }
    return self;
}

- (void)dealloc
{
}

-(void)initUI
{
    self.view.backgroundColor = [UIColor colorWithRed:226.0/255.0 green:231.0/255.0 blue:237.0/255.0 alpha:1.0];
    
    [self createTitle];
    self.mtitle.text = @"";
    
    UIImageView *sexbg = [[UIImageView alloc] initWithFrame:CGRectMake(110, 7, 100, 29)];
    sexbg.image = [UIImage imageNamed:@"icon_online_bg.png"];
    [self.view addSubview:sexbg];
    
    manbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    manbtn.frame = CGRectMake(160, 7, 50, 29);
    [manbtn setImage:[UIImage imageNamed:@"icon_online_man.png"] forState:UIControlStateNormal];
    [manbtn setImage:[UIImage imageNamed:@"icon_online_mandis.png"] forState:UIControlStateDisabled];
    [manbtn addTarget:self action:@selector(manpress) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:manbtn];
    
    womenbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    womenbtn.frame = CGRectMake(110, 7, 50, 29);
    [womenbtn setImage:[UIImage imageNamed:@"icon_online_women.png"] forState:UIControlStateNormal];
    [womenbtn setImage:[UIImage imageNamed:@"icon_online_womendis.png"] forState:UIControlStateDisabled];
    [womenbtn addTarget:self action:@selector(womenpress) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:womenbtn];

    
    if ([DataControl shareControl].personDS.uinfo.sex == 1) {
        setOnLineOrder(OLOT_FAMALE);
        
        manbtn.enabled = NO;
        womenbtn.enabled = YES;
    }
    else
    {
        setOnLineOrder(OLOT_MALE);
        
        manbtn.enabled = YES;
        womenbtn.enabled = NO;
    }
    
    
    mtable =[[UITableView alloc]initWithFrame:CGRectMake(0, 44, WINDOW_WIDTH, WINDOW_HIGTH - TOPBAR_HIGHT-49 - 20)
                                        style:UITableViewStylePlain];
    mtable.backgroundColor = CELL_BG_COLOR;
    mtable.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    mtable.delegate =self;
    mtable.dataSource =self;
    [self.view insertSubview:mtable belowSubview:self.mtitle];
    
    
    if (_refreshHeaderView == nil) {
        EGORefreshTableHeaderView * view1 = [[EGORefreshTableHeaderView alloc] initWithFrame:
                                             CGRectMake(0.0f,
                                                        10.0f - mtable.bounds.size.height,
                                                        mtable.frame.size.width,
                                                        self.view.bounds.size.height - TOPBAR_HIGHT - 59)];
        
        view1.delegate = self;
        [mtable addSubview:view1];
        _refreshHeaderView = view1;
    }
    [_refreshHeaderView refreshLastUpdatedDate];
    
    
    
    
    
    
}

#pragma mark - private fun -

-(void)manpress
{
    manbtn.enabled = NO;
    womenbtn.enabled = YES;
    
    [[netManager sharedNetManager].sendonline sendonline:1];
    
    setOnLineOrder(OLOT_MALE);
    
    [self refreshView];
    
    if (iGameState != OLGS_START) {
        
        [[ViewManager sharedViewManager] showProgressHUDWithStatus:@"正在查询"
                                                          withView:self.view];
        
        iTimeCount = 0;
        iGameState = OLGS_START;
        
    }
}

-(void)womenpress
{
    manbtn.enabled = YES;
    womenbtn.enabled = NO;
    
    [[netManager sharedNetManager].sendonline sendonline:2];
    
    setOnLineOrder(OLOT_FAMALE);
    
    [self refreshView];
    
    if (iGameState != OLGS_START) {
        
        [[ViewManager sharedViewManager] showProgressHUDWithStatus:@"正在查询"
                                                          withView:self.view];
        
        iTimeCount = 0;
        iGameState = OLGS_START;
        
    }
}

-(void)InitSwitch
{
    if ([DataControl shareControl].personDS.uinfo.sex == 1) {
        
        [[netManager sharedNetManager].sendonline sendonline:2];
        
        setOnLineOrder(OLOT_FAMALE);
        
        manbtn.enabled = YES;
        womenbtn.enabled = NO;
    }
    else
    {
        
        [[netManager sharedNetManager].sendonline sendonline:1];
        
        setOnLineOrder(OLOT_MALE);
        
        manbtn.enabled = NO;
        womenbtn.enabled = YES;
    }
    
    
}

-(void)viewWillShow
{
    if (iGameState != OLGS_START) {
        
        [[ViewManager sharedViewManager] showProgressHUDWithStatus:@"正在查询"
                                                          withView:self.view];
        
        iTimeCount = 0;
        iGameState = OLGS_START;
        
    }
    
}

-(void)UICustomTick
{
    switch (iGameState) {
        case OLGS_START:
        {
            if (iTimeCount < 300) {
                iTimeCount++;
            }
            else
            {
                iTimeCount = 0;
                iGameState = OLGS_NULL;
                
                [[ViewManager sharedViewManager] dismissProgressHUD];
                
                [[DataControl shareControl].OnlinePeoDS RemoveAll];
                
                [self refreshView];
            }
        }
            break;
            
        default:
            break;
    }
}

-(void)OnlineRequestBakc
{
    [[ViewManager sharedViewManager] dismissProgressHUD];
    
    [mtable reloadData];
    
    iTimeCount = 0;
    iGameState = OLGS_NULL;
}

#pragma mark - 加载数据
-(void)FirstLoadingData{
    //刷新的表尾
    _footerView = [[RefreshTableFooterView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
    _footerView.hidden = YES;
    mtable.tableFooterView = _footerView;
    
    flag = 0;//标记从总的数据源中转到小的数据源中多少次
    count = [[DataControl shareControl].OnlinePeoDS GetShowArrCount];//得出总的数据源中元素的个数
    
    if (!_datasArr) {
        _datasArr = [[NSMutableArray alloc] init];
    }else{
        [_datasArr removeAllObjects];
    }
    
    if ([[DataControl shareControl].OnlinePeoDS GetShowArrCount] >= 20) {
        for (int i = 0; i < 20; i++) {
            [_datasArr  addObject:[[DataControl shareControl].OnlinePeoDS GetObjectByIndex:i]];
        }
    }
    [mtable reloadData];
}


-(void)refreshView
{
    [mtable reloadData];
    
}

#pragma mark - tableView DataSource -
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if ([DataControl shareControl].OnlinePeoDS != nil) {
        return [_datasArr count];
        
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section=[indexPath section];
    NSUInteger row = [indexPath row];
    
    static NSString * CellIdentifier = @"Cell";
    PersonCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[PersonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
		cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    
    
    switch (section)
    {
        case 0:
        {
            if ([DataControl shareControl].OnlinePeoDS != nil && row < [[DataControl shareControl].OnlinePeoDS GetShowArrCount]) {
                
                NSString *mail = [[DataControl shareControl].OnlinePeoDS GetObjectByIndex:row];
                FirendInfo *fi = [[DataControl shareControl] SearchInfo:mail];
                
                int isex = [[DataControl shareControl].OnlinePeoDS GetOnlinePeopleOrder]
                == OLOT_MALE ? 1:2;
                
                if (fi != nil && fi.sex == isex)
                {
                    NSString *url = [[DataControl shareControl] SearchHeadImage:mail];
                    
                    [[ViewManager sharedViewManager] dismissProgressHUD];
                    cell.nameLabel.text = fi.name;//昵称
                    cell.signLabel.text = fi.strSign;//个人签名
                    cell.ageLabel.text = [NSString stringWithFormat:@"%d",fi.age];//年龄
                    
                    if (fi.sex == 1) {
                        cell.sexicon.image = [UIImage imageNamed:@"icon_male.png"];
                    }else{
                        cell.sexicon.image = [UIImage imageNamed:@"icon_female.png"];
                    }
                    if ([url length] > 0)
                    {
                        cell.imageView.image = [UIImage imageNamed:@"default_head.png"];
                        UIImage *headImage = [UIImage imageWithContentsOfFile:url];
                        if (headImage) {
                            cell.imageView.image = nil;
                            cell.headImageView.image = [UIImage imageWithContentsOfFile:url];
                        }
                    }else{
                        cell.headImageView.image = nil;
                        cell.imageView.image = [UIImage imageNamed:@"default_head.png"];
                    }
                    
                    
                }
                else{
                    cell.imageView.image = [UIImage imageNamed:@"default_head.png"];
                }
                
                if (fi != nil  && fi.sex != isex) {
                    [[DataControl shareControl].OnlinePeoDS RemoveObjectByIndex:row];
                    
                    [mtable reloadData];
                }
                
                
            }
            
            
        }
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            break;
        default:
            break;
    }
    
    //    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//推界面提示角标
    [cell changeCellSize];//动态控制控件的坐标
    
    
    return cell;
}

#pragma mark -table delegate-
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch ([indexPath section]) {
        case 0:
        {
            if ([DataControl shareControl].OnlinePeoDS != nil)
            {
                int row = [indexPath row];
                if (row >=0 && row < [[DataControl shareControl].OnlinePeoDS GetShowArrCount])
                {
                    NSString *mail = [[DataControl shareControl].OnlinePeoDS GetObjectByIndex:row];
                    FirendInfo *fi = [[DataControl shareControl] SearchInfo:mail];
                    if(fi != nil)
                    {
                        [[DataControl shareControl] setCurrentFI:fi];
                        [[ViewManager sharedViewManager] showView:VI_PERSONINFO
                                                 withIsRemoveCurV:false
                                                    withDirection:VD_RIGHT];
                    }
                }
                
            }
        }
            break;
            
        default:
            break;
    }
}

#pragma mark –
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
    
    if ([[DataControl shareControl].OnlinePeoDS GetOnlinePeopleOrder] == OLOT_MALE) {
        [[netManager sharedNetManager].sendonline sendonline:1];
    }
    else
    {
        [[netManager sharedNetManager].sendonline sendonline:2];
    }
    
    [[DataControl shareControl].taskDS CompleteTaskByID:TI_F_ONLINEPEOPLE
                                       withIsDirectShow:true];
    
    
    _reloading = YES;
}

- (void)doneLoadingTableViewData{
    _reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:mtable];
}


#pragma mark –
#pragma mark UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
	if (mtable.contentOffset.y == mtable.contentSize.height - mtable.frame.size.height)
    {
        [_footerView RefreshScrollViewDidScroll:scrollView];
        
    }else{
        
        [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if (mtable.contentOffset.y > (mtable.contentSize.height - mtable.frame.size.height)) {
        
        [UIView animateWithDuration:3.0 animations:^{
            [_footerView RefreshScrollViewDidEndDragging:scrollView];//调用拖动结束的时候
        } completion:^(BOOL finished) {
            [self RefreshLoadingData];//加载数据
            [_footerView RefreshScrollViewDataSourceDidFinishedLoading:scrollView];//调用加载完数据的时候
        }];
        
    }else if (mtable.contentOffset.y <= 0){
        [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
    
}

#pragma mark - 刷新数据
-(void)RefreshLoadingData{
    flag++;
    
    if ([_datasArr count] != count) {
        if ((count - [_datasArr count]) > 0 && (count - [_datasArr count]) < 20) {
            
            for (int i = flag * 20; i < count; i++) {
                [_datasArr  addObject:[[DataControl shareControl].OnlinePeoDS GetObjectByIndex:i]];//通过index取得当前的原色
            }
        }else if ((count - [_datasArr count]) > 20){
            
            for (int i = 0; i < 20; i++) {
                [_datasArr  addObject:[[DataControl shareControl].OnlinePeoDS GetObjectByIndex:(i + 20*flag)]];
            }
        }
        
        [mtable reloadData];
        
    }else{
        mtable.contentSize = CGSizeMake(320, mtable.contentSize.height - _footerView.frame.size.height);
        _footerView.frame = CGRectZero;
    }
}


#pragma mark –
#pragma mark EGORefreshTableHeaderDelegate Methods
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    [self reloadTableViewDataSource];
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    return _reloading;
}
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    return [NSDate date];
}

@end
